package com.application.Activity;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.webkit.MimeTypeMap;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.RemoteViews;
import android.widget.SlidingDrawer;

import com.application.Controller.ReadWriteFileController;
import com.application.Network.Protocol;
import com.application.outdoor.InvoikeServices.CommonInvoike;
import com.application.outdoor.InvoikeServices.CustomMultiPartEntity;
import com.application.outdoor.InvoikeServices.CustomMultiPartEntity.ProgressListener;
import com.application.outdoor.adapter.FileShareAdapter;
import com.application.outdoor.pojo.FileSharePOJO;
import com.application.outdoor.pojo.NhomPOJO;

public class od_ShareFileActivity extends Activity {
	private static int SHARE_FILE_CODE = 1;
	private static final int CAMERA_REQUEST = 1888;
	private static String UPLOAD_URL = Protocol.SERVER_URL + "/FileUploadServlet";
	public static String DOWNLOAD_URL = Protocol.SERVER_URL + "/FileDownloadServlet";
	private static boolean isDownloading = false;
	String mineType = "";
	Notification notifUpload;
	Notification notifDownload;
	NotificationManager notificationManager;
	private static int UPLOAD_NOF_ID = 89;
	public static int DOWNLOAD_NOF_ID = 90;
	long cUpTime = 0;
	long cDownTime = 0;
	Button btnUpFile, btnChupHinh;
	ListView lvDanhSachFile;
	static  FileShareAdapter adapter;
	static ArrayList<FileSharePOJO> lstFile;
	String selectFilePath = "";
	ProgressDialog pd;
	int postion;
	public static int idNhom = -1;
	public static boolean isOpen=false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.od_activity_share_file);
		btnUpFile = (Button) findViewById(R.id.btnUpFile);
		btnChupHinh = (Button) findViewById(R.id.btnChupHinh);
		lvDanhSachFile = (ListView) findViewById(R.id.lvDanhSachFile);

		registerForContextMenu(lvDanhSachFile);

		btnUpFile.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(od_ShareFileActivity.this, FrmSelectFile.class);
				intent.putExtra(FrmSelectFile.SELECTION_MODE, FrmSelectFile.MODE_OPEN);
				startActivityForResult(intent, SHARE_FILE_CODE);
			}
		});
		btnChupHinh.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
				startActivityForResult(cameraIntent, CAMERA_REQUEST);

			}
		});
		getFile();
		fillList(lstFile);
		isOpen=true;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.od_activity_share_file, menu);
		return true;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		if (v.getId() == R.id.lvDanhSachFile) {
			AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;

			menu.addSubMenu(Menu.NONE, 1, 1, "Tải file");
			menu.addSubMenu(Menu.NONE, 2, 2, "Xóa file");
			// menu.addSubMenu(Menu.NONE, 3, 3, "Chat");
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
		postion = info.position;
		int menuItemIndex = item.getItemId();
		if (menuItemIndex == 1) {
			// Tải file
			try {
				Intent fileOpen = new Intent(od_ShareFileActivity.this, FrmSelectFile.class);
				fileOpen.putExtra(FrmSelectFile.FILE_NAME, lstFile.get(postion).getTenFile());
				startActivityForResult(fileOpen, SHARE_FILE_CODE);

			} catch (Exception e) {
				Log.d("Phu", "mạng có vấn đề " + e.getMessage());
			}
		} else if (menuItemIndex == 2) {
			// Xóa file
		}
		return true;
	}

	@Override
	public synchronized void onActivityResult(final int requestCode, int resultCode, final Intent data) {
		
		if (requestCode == SHARE_FILE_CODE && resultCode == RESULT_OK) {
			String rsType = data.getStringExtra(FrmSelectFile.RESULT_TYPE);
			selectFilePath = data.getStringExtra(FrmSelectFile.RESULT_PATH);
			Log.d(Protocol.TAG, "selectFilePath " + selectFilePath);
			// Up
			if (rsType != null && rsType.equals("2")) {
				
				AlertDialog.Builder builder = new AlertDialog.Builder(od_ShareFileActivity.this);
				builder.setTitle("Chia sẻ tài liệu-[Nhập mô tả]");
				final EditText txtGhiChu = new EditText(od_ShareFileActivity.this);
				//mới edit
				LayoutParams weigh=new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT,0.6f);
				txtGhiChu.setLayoutParams(weigh);
				//
				builder.setView(txtGhiChu);
				builder.setPositiveButton("Chia sẻ", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// File f = new File(selectFilePath);
						String ghiChu = txtGhiChu.getText().toString();
						new UploadFileTask().execute(selectFilePath, CommonUtilities.nguoiDung.getTenDangNhap(), idNhom
								+ "", ghiChu);
						
					}
				});
				builder.setNegativeButton("Hủy bỏ", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						
					}

				});
				builder.create().show();

			}// Down
			else if (rsType != null && rsType.equals("1")) {
				Log.d(Protocol.TAG, "file id=" + lstFile.get(postion).getId());
				FileSharePOJO f = lstFile.get(postion);
				od_fileInfoActivity.file = new FileSharePOJO();
				od_fileInfoActivity.file.setId(f.getId());
				od_fileInfoActivity.file.setIdNhom(f.getIdNhom());
				od_fileInfoActivity.file.setNguoiUp(f.getNguoiUp());
				od_fileInfoActivity.file.setPath(selectFilePath);
				od_fileInfoActivity.file.setTenFile(f.getTenFile());
				od_fileInfoActivity.file.setThoiGian(f.getThoiGian());
				new DownloadFileTask().execute(lstFile.get(postion).getId() + "", selectFilePath);
			}
		} else if (requestCode == CAMERA_REQUEST) {
			if(data==null||data.getExtras()==null)
				return;
			Object resultPhoto = data.getExtras().get("data");
			if (resultPhoto == null)
				return;
			final Bitmap photo = (Bitmap) resultPhoto;
			LinearLayout linearLayout = new LinearLayout(getBaseContext());
			linearLayout.setOrientation(LinearLayout.VERTICAL);
			ImageView img = new ImageView(getBaseContext());
			
			img.setImageBitmap(photo);
			final EditText txtGhiChu = new EditText(getBaseContext());
			txtGhiChu.setHeight(14);
			
			//truc edit
			
			LayoutParams weighImg=new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT,0.5f);
			img.setLayoutParams(weighImg);
			LayoutParams weigh=new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT,0.6f);
			txtGhiChu.setLayoutParams(weigh);
			//
			linearLayout.addView(img);
			linearLayout.addView(txtGhiChu);

			AlertDialog.Builder builder = new AlertDialog.Builder(od_ShareFileActivity.this);
			builder.setTitle("Chia sẻ");
			builder.setView(linearLayout);
			builder.setPositiveButton("Chia sẻ", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					String path = ReadWriteFileController.DIRECTORY + "photo_" + System.currentTimeMillis() + ".jpg";

					try {
						File f = new File(path);
						FileOutputStream fos = new FileOutputStream(f);
						photo.compress(CompressFormat.JPEG, 80, fos);
						fos.flush();
						fos.close();
						String ghiChu = txtGhiChu.getText().toString();
						new UploadFileTask().execute(path, CommonUtilities.nguoiDung.getTenDangNhap(), idNhom + "",
								ghiChu);
					} catch (Exception e) {
						// MESApplication.showDialog(od_ShareFileActivity.this,
						// "Lỗi","Share file mới chụp: "+ e.getMessage());
						Log.e(Protocol.TAG, "share file hinh");
					}
					
				}
			});
			builder.setNegativeButton("Hủy bỏ", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					
				}

			});
			builder.create().show();
		}
	}

	private void getFile() {
		try {
			String data = new CommonInvoike().getFileCuaNhom(idNhom);
			lstFile = FileSharePOJO.parseList(data);
		} catch (Exception e) {
			Log.d(Protocol.TAG, "od_ShareFile.getFile: Không lấy đc danh sách file!");
		}
	}

	private void fillList(ArrayList<FileSharePOJO> data) {
		adapter = new FileShareAdapter(getApplication(), data);
		this.lvDanhSachFile.setAdapter(adapter);
	}

	private class DownloadFileTask extends AsyncTask<String, Integer, String> {

		@Override
		protected String doInBackground(String... params) {
			try {
				isDownloading = true;

				notifDownload.contentView.setTextViewText(R.id.status_text, "Đang tải về: " + params[1]);
				URL url = new URL(DOWNLOAD_URL + "?" + Protocol.ID + "=" + params[0]);
				URLConnection connection = url.openConnection();
				connection.connect();

				InputStream input = new BufferedInputStream(url.openStream());
				OutputStream output = new FileOutputStream(params[1]);

				int fileLength = connection.getContentLength();

				byte data[] = new byte[1024];
				long total = 0;
				int count;
				long currentTime = 0;
				while ((count = input.read(data)) != -1) {
					total += count;
					currentTime = System.currentTimeMillis();
					if (currentTime - cDownTime > 500) {
						publishProgress((int) (total * 100 / fileLength));
						cDownTime = currentTime;
					}
					output.write(data, 0, count);
				}

				output.flush();
				output.close();
				input.close();
			} catch (Exception e) {
				Log.d(Protocol.TAG, "Download file bi loi:" + e.getMessage());
				isDownloading = false;
			}
			try {
				Thread.sleep(2000);
			} catch (Exception e) {
				// TODO: handle exception
			}
			return params[1];

		}

		@Override
		protected void onProgressUpdate(Integer... progress) {
			notifDownload.contentView.setProgressBar(R.id.status_progress, 100, progress[0], false);
			notificationManager.notify(DOWNLOAD_NOF_ID, notifDownload);

		}

		@Override
		protected void onPostExecute(String ui) {
			notificationManager.cancel(DOWNLOAD_NOF_ID);
			isDownloading = false;
			GCMIntentService.notification(getBaseContext(), "Đã tải xong tập tin: " + ui, od_fileInfoActivity.class,
					null);
		}

		@Override
		protected void onPreExecute() {
			initDownload();
			notificationManager.notify(DOWNLOAD_NOF_ID, notifDownload);
		}
	}

	private class UploadFileTask extends AsyncTask<String, Integer, String> {
		long totalSize;
		int percent;

		@Override
		protected String doInBackground(String... args) {
			HttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(UPLOAD_URL);
			notifUpload.contentView.setTextViewText(R.id.status_text,
					"Đang tải lên: " + args[0].substring(args[0].lastIndexOf("/"), args[0].length()));

			Log.d(Protocol.TAG, "Bắt đầu up file");
			Log.d(Protocol.TAG, "URL= " + UPLOAD_URL);
			Log.d(Protocol.TAG, "file up=" + args[0]);
			try {
				CustomMultiPartEntity multipartContent = new CustomMultiPartEntity(new ProgressListener() {
					@Override
					public void transferred(long num) {
						percent = (int) ((num / (float) totalSize) * 100);
						if (System.currentTimeMillis() - cUpTime > 500) {
							publishProgress(percent);
							cUpTime = System.currentTimeMillis();
						}
					}
				});

				// We use FileBody to transfer an image
				multipartContent.addPart("file", new FileBody(new File(args[0])));
				multipartContent.addPart(Protocol.NGUOI_DUNG, new StringBody(args[1]));
				multipartContent.addPart(Protocol.ID_NHOM, new StringBody(args[2]));
				multipartContent.addPart(Protocol.GHI_CHU, new StringBody(args[3]));
				totalSize = multipartContent.getContentLength();
				// Send it
				httpPost.setEntity(multipartContent);
				HttpResponse response = httpClient.execute(httpPost);
				BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
				String line = "";
				int i = 50;
				int j = 0;
				while ((line = br.readLine()) != null) {
					if (System.currentTimeMillis() - cUpTime > 500) {
						Log.d("Phu", "line= " + line);
						i = Integer.parseInt(line);
						j = i + percent / 2;
						publishProgress((j > 95 ? 95 : j));
						cUpTime = System.currentTimeMillis();
					}
				}
			} catch (Exception e) {
				Log.d("Phu", "Dính lỗi rồi: " + e.getMessage());
			}
			return args[0].substring(args[0].lastIndexOf("/"), args[0].length());
		}

		@Override
		protected void onProgressUpdate(Integer... progress) {
			notifUpload.contentView.setProgressBar(R.id.status_progress, 100, progress[0], false);
			notificationManager.notify(UPLOAD_NOF_ID, notifUpload);

		}

		@Override
		protected void onPostExecute(String ui) {
			notificationManager.cancel(UPLOAD_NOF_ID);
			GCMIntentService.notification(getBaseContext(), "Đã tải lên tập tin:" + ui, null, null);
		}

		@Override
		protected void onPreExecute() {
			initUpload();
			notificationManager.notify(UPLOAD_NOF_ID, notifUpload);
		}
	}

	private void initDownload() {

		// Intent intent=new Intent(getBaseContext(),od_fileInfoActivity.class);
		PendingIntent pendingIntent = PendingIntent.getActivity(getBaseContext(), 0, null, 0);
		notifDownload = new Notification(R.drawable.icon, "Tải tài liệu", System.currentTimeMillis());
		notifDownload.flags |= Notification.FLAG_ONGOING_EVENT;
		notifDownload.contentView = new RemoteViews(getApplicationContext().getPackageName(),
				R.layout.od_download_progress);
		notifDownload.contentIntent = pendingIntent;
		notifDownload.contentView.setImageViewResource(R.id.status_icon, R.drawable.ic_file_download);
		notifDownload.contentView.setProgressBar(R.id.status_progress, 100, 0, false);
		notificationManager = (NotificationManager) getApplicationContext().getSystemService(
				Context.NOTIFICATION_SERVICE);
	}

	private void initUpload() {
		PendingIntent pendingIntent = PendingIntent.getActivity(getBaseContext(), 0, null, 0);
		notifUpload = new Notification(R.drawable.icon, "Chia sẻ tài liệu", System.currentTimeMillis());
		notifUpload.flags |= Notification.FLAG_ONGOING_EVENT;
		notifUpload.contentView = new RemoteViews(getApplicationContext().getPackageName(),
				R.layout.od_download_progress);
		notifUpload.contentIntent = pendingIntent;
		notifUpload.contentView.setImageViewResource(R.id.status_icon, R.drawable.ic_file_upload);
		notifUpload.contentView.setProgressBar(R.id.status_progress, 100, 0, false);
		notificationManager = (NotificationManager) getApplicationContext().getSystemService(
				Context.NOTIFICATION_SERVICE);
	}
	@Override
	public void onDestroy(){
		super.onDestroy();
		isOpen=false;
	}
	@Override 
	public void onResume(){
		super.onResume();
		isOpen=true;
	}
	public static void addFile(FileSharePOJO file){
		lstFile.add(file);
		adapter.notifyDataSetChanged();
	}
}
